<template>
  <div class="fillcontain">
    <div class="mb10 pl20">
      <bt-col-header title="决策表"></bt-col-header>

      <div class="row padding-button">
        <div class="col-md-12 button-flex">
          <el-button v-if="!isconflict" type="info" plain @click.native="addRow()">新增行</el-button>
          <el-button type="info" plain @click="addConditionCol('1')">新增条件列
          </el-button>
          <el-button type="info" plain @click="addConditionCol('2')">新增动作列
          </el-button>
          <el-button type="info" plain @click="editHeader()">编辑表头</el-button>
          <el-button type="info" plain @click="downExcel()">导出</el-button>
          <el-upload style="margin-left: 10px" multiple action="#" :auto-upload="true" :limit="1" :before-upload="beforeAvatarUpload" :file-list="fileList">
            <el-button type="info" plain>上传</el-button>
          </el-upload>
        </div>
      </div>
    </div>

    <div class="contain">
      <!-- 列表 -->
      <el-table :data="tableDatas.slice((page.pageIndex-1)*page.pageSize,page.pageIndex*page.pageSize)" max-height="700" border v-if="conditionList.length">
        <el-table-column align="center" v-for="(col, i) in conditionList" :render-header="labelHead" :property="col.decisionCode" :key="i+Math.random()" :index="i" :label="col.conditionDesc">
          <!-- <template slot="header" slot-scope="scope">
            <el-tooltip
              v-if="
                conditionList[scope.column.index] &&
                conditionList[scope.column.index].headType == '0'
              "
              class="item"
              effect="dark"
              :content="scope.column.label"
              placement="top"
            >
              {{ scope.column.label }}
            </el-tooltip>
            <el-tooltip
              v-if="
                conditionList[scope.column.index] &&
                conditionList[scope.column.index].headType == '1'
              "
              class="item"
              effect="dark"
              :content="scope.column.label + '(条件)'"
              placement="top"
            >
              <span>
                <i
                  v-if="showDel"
                  class="el-icon-circle-close"
                  @click="delcol( scope.column)"
                ></i>
                {{ scope.column.label }} (条件)
              </span>
            </el-tooltip>
            <el-tooltip
              v-if="
                conditionList[scope.column.index] &&
                conditionList[scope.column.index].headType == '2'
              "
              class="item"
              effect="dark"
              :content="scope.column.label + '(动作)'"
              placement="top"
            >
              <span>
                <i
                  v-if="showDel"
                  class="el-icon-circle-close"
                  @click="delcol(scope, scope.column)"
                ></i>
                {{ scope.column.label }} (动作)
              </span>
            </el-tooltip>
          </template> -->
          <template slot-scope="scope">
            <div v-if="scope.row[scope.column.property]">
              {{ getItemValue(scope.row, scope.column) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" width="240" label="操作" fixed="right">
          <template slot-scope="scope">
            <el-button v-if="!isconflict" type="text" size="small" @click="addDecisionRow(scope.row, scope.$index)">
              复制
            </el-button>
            <!-- :disabled="scope.row[scope.column.property].isEffect===0 ? true : false" -->
            <el-button v-if="scope.row && scope.row['RCODE']" @click.native="addRow(scope.row, scope.$index)" :disabled="
                scope.row['RCODE'].isEffect == '0'
                  ? true
                  : false
              " type="text" size="small">修改
            </el-button>
            <span v-if="!isconflict">
              <el-button v-if="scope.row.RCODE.isEffect==='1'
                " type="text" size="small" @click="editIsEffect(scope, 0)">
                禁用
              </el-button>
              <el-button v-if="scope.row.RCODE.isEffect==='0'
                " type="text" size="small" @click="editIsEffect(scope, 1)">
                启用
              </el-button>
            </span>
            <el-button type="text" size="small" @click="delDecision(scope)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="row" v-if="conditionList.length">
        <div class="col-md-12 text-right">
          <div class="pagination">
            <!-- 分页 -->
            <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="page.pageIndex" :page-sizes="[10, 20, 50, 100]" :page-size="page.pageSize" :total="tableDatas.length" layout="total, sizes, prev, pager, next, jumper">
            </el-pagination>
          </div>
        </div>
      </div>
    </div>

    <!-- 弹窗, 添加条件 -->
    <!--       v-if="addConditionVisible" -->
    <add-condition :isconflict="isconflict" ref="addCondition" :visible="addConditionVisible" :entityList="checkEntity" :chooseIndex="chooseIndex" :conditionList="conditionList" @refreshDataList="getConditionDataList" @cancel="closeAddCondition"></add-condition>
    <!-- 弹窗, 添加动作 -->
    <!-- v-if="addactionVisible" -->
    <add-action :isconflict="isconflict" ref="addaction" :entityList="checkEntity" :chooseIndex="chooseIndex" :actionList="conditionList" @refreshDataList="getConditionDataList"></add-action>

    <!-- 弹窗, 表头 -->
    <edit-condition v-if="editConditionVisible" ref="editCondition" :entityList="entityList" :chooseIndex="colIndex" :conditionList="conditionList" @refreshDataList="getConditionData"></edit-condition>

    <!-- 弹窗, 填值 -->
    <el-dialog title="详情" :close-on-click-modal="false" width="60%" :visible.sync="addvisible" append-to-body id="condition-dialog">
      <el-form ref="dataForm" @keyup.enter.native="adddataFormSubmit()" label-width="80px">
        <div class="col-md-6" v-for="(item, index) in adddataForm" :key="index">
          <rules-input v-if="item && item.headType == '0'">
            <template slot="ruleinput">
              <el-input v-if="item && item.decisionCode == 'RCODE'" v-model="item.conditionDesc" disabled placeholder="请输入内容"></el-input>
              <el-input v-else v-model="item.conditionDesc" placeholder="请输入内容"></el-input>
            </template>
            <template v-if="item && item.headType == '0'" slot="inputdes">
              {{ item["conditionDesc1"] }}
            </template>
          </rules-input>
          <!-- 条件 -->
          <rules-input v-if="item && item.headType == '1'">
            <!-- 非方法 固定值 -->
            <template v-if="item && item.iszhixing" slot="ruleinput">
              <el-select v-model="item.isExcute" filterable clearable placeholder="请选择">
                <el-option v-for="(i, index) in excuteTypes" :key="index" :label="i.label" :value="i.value" @click.native="changeExeType(item, index)">
                </el-option>
              </el-select>
            </template>
            <template v-if="item && item.conditionType == '4' && item.divisor" slot="ruleinput">
              <!-- 规则因子 非方法 且文本类型 则是输入框-->
              <el-input v-if="
                  item.divisor.valueType === '2' &&
                  item.divisor.divisorType === '0' &&
                  item.divisor.itemValueType === '1'
                " v-model="item.rightValue" @blur="insertV('41', item)" placeholder="文本值"></el-input>
              <!-- 规则因子 非方法 且枚举类型 则是下拉框-->
              <el-select v-if=" item.divisor.divisorType === '0' && item.divisor.valueType === '2' && item.divisor.itemValueType === '2'" v-model="item.rightValue" filterable clearable placeholder="请选择条件">
                <el-option v-for="(i, index) in enumList[`${item.divisor.id}list`]" :key="index" :label="i.label" :value="i.enumCode" @click.native="insertV('42', item, i)">
                </el-option>
              </el-select>
              <!-- 规则因子 非方法 且模型类型 则是模型-->
              <el-select v-if=" item.divisor.divisorType === '0' && item.divisor.valueType === '2' && item.divisor.itemValueType === '3'" v-model="item.rightEntityId" filterable clearable placeholder="请选择模型">
                <el-option v-for="(i, index) in checkEntity" :key="index" :label="i.entityName" :value="i.entityId" @click.native="insertV('43', item, i)">
                </el-option>
              </el-select>
              <!--模型属性选择  -->
              <el-select v-if=" item.divisor.divisorType === '0' && item.divisor.valueType === '2' && item.divisor.itemValueType === '3'" v-model="item.rightProperty" filterable clearable placeholder="请选择属性">
                <el-option v-for="(i, index) in childList[`${item.rightEntityId}list`]" :key="index" :label="i.label" :value="i.itemId" @click.native="insertV('44', item, i)">
                </el-option>
              </el-select>
              <!--方法参数-->
              <div class="col-md-12" v-if=" item.divisor.divisorType === '1' && item.divisorMethodParams">
                <div class="col-md-6" v-for="(p, index) in item.divisorMethodParams" :key="index">
                  <div class="col-md-12">
                    <el-select v-if="p.valueType === '2'" v-model="p.name" filterable placeholder="值类型">
                      <el-option v-for="(item, index) in item.divisormethodEnum[index]" :key="index" :label="item.label" :value="item.value">
                      </el-option>
                    </el-select>
                    <el-input v-else v-model="p.name" @blur="insertV('45', item, p)" :placeholder="p.desc"></el-input>
                  </div>
                </div>
              </div>
              <!--自定义参数-->
              <div class="col-md-12" v-if=" item.divisor.divisorType === '3' && item.divisorMethodParams">
                <div class="col-md-6" v-for="(p, index) in item.divisorMethodParams" :key="index">
                  <div class="col-md-12">
                    <el-select v-if="p.valueType === '2'" v-model="p.name" filterable placeholder="值类型">
                      <el-option v-for="(item, index) in item.divisormethodEnum[index]" :key="index" :label="item.label" :value="item.value">
                      </el-option>
                    </el-select>
                    <el-input v-else v-model="p.name" @blur="insertV('45', item, p)" :placeholder="p.desc"></el-input>
                  </div>
                </div>
              </div>
            </template>
            <template v-if="item && item.headType == '1'" slot="inputdes">
              {{ item["conditionDesc1"] + "(条件)" }}
            </template>
          </rules-input>
          <rules-input v-if="item && item.headType == '2'">
            <template v-if="item && item.iszhixing" slot="ruleinput">
              <el-select v-model="item.isExcute" filterable clearable placeholder="请选择">
                <el-option v-for="(i, index) in excuteTypes" :key="index" :label="i.label" :value="i.value" @click.native="changeExeType(item, index)">
                </el-option>
              </el-select>
            </template>
            <!-- 规则因子 -->
            <template v-if="item && item.conditionType == '4' && item.divisor" slot="ruleinput">
              <el-input v-if=" item.divisor.valueType === '2' && item.divisor.divisorType === '0' && item.divisor.itemValueType === '1'" v-model="item.rightValue" @blur="insertV('41', item)" placeholder="文本值"></el-input>
              <!-- 规则因子 非方法 且枚举类型 则是下拉框-->
              <el-select v-if=" item.divisor.divisorType === '0' && item.divisor.valueType === '2' && item.divisor.itemValueType === '2'" v-model="item.rightValue" filterable clearable placeholder="请选择条件">
                <el-option v-for="(i, index) in actionEnumList[`${item.divisor.id}list`]" :key="index" :label="i.label" :value="i.enumCode" @click.native="insertV('42', item, i)">
                </el-option>
              </el-select>
              <!-- 规则因子 非方法 且模型类型 则是模型-->
              <el-select v-if=" item.divisor.divisorType === '0' && item.divisor.valueType === '2' && item.divisor.itemValueType === '3'" v-model="item.rightEntityId" filterable clearable placeholder="请选择模型">
                <el-option v-for="(i, index) in checkEntity" :key="index" :label="i.entityName" :value="i.entityId" @click.native="insertV('43', item, i)">
                </el-option>
              </el-select>
              <!--  -->
              <el-select v-if=" item.divisor.divisorType === '0' && item.divisor.valueType === '2' && item.divisor.itemValueType === '3'" v-model="item.rightProperty" filterable clearable placeholder="请选择属性">
                <el-option v-for="(i, index) in childList[`${item.rightEntityId}list`]" :key="index" :label="i.label" :value="i.itemId" @click.native="insertV('44', item, i)">
                </el-option>
              </el-select>
              <!-- 规则因子 方法-->
              <div class="col-md-12" v-if=" item.divisor.divisorType === '1' && item.divisorMethodParams">
                <div class="col-md-6" v-for="(p, index) in item.divisorMethodParams" :key="index">
                  <div class="col-md-6">
                    <el-input v-if="p.valueType != '2'" v-model="p.name" :placeholder="p.desc"></el-input>
                    <el-select v-if="p.valueType === '2'" v-model="p.name" filterable placeholder="值类型">
                      <el-option v-for="(item, index) in item.divisormethodEnum[index]" :key="index" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                  </div>
                </div>
              </div>
              <!-- 自定义动作-->
              <div class="col-md-12" v-if=" item.divisor.divisorType === '3' && item.divisorMethodParams">
                <div class="col-md-6" v-for="(p, index) in item.divisorMethodParams" :key="index">
                  <div class="col-md-6">
                    <el-input v-if="p.valueType != '2'" v-model="p.name" :placeholder="p.desc"></el-input>
                    <el-select v-if="p.valueType === '2'" v-model="p.name" filterable placeholder="值类型">
                      <el-option v-for="(item, index) in item.divisormethodEnum[index]" :key="index" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                  </div>
                </div>
              </div>
            </template>
            <template v-if="item && item.headType == '2'" slot="inputdes">
              {{ item["conditionDesc1"] + "(动作)" }}
            </template>
          </rules-input>
        </div>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button type="info" plain @click="adddataFormSubmit('dynamicValidateForm')">确定</el-button>
        <el-button @click="addvisible = false">返回</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { entityList, entityItemList } from "@/api/baseConfig/entity";
import { getData, getEnum } from "@/api/baseConfig/conditionDivisor";
import {
  getActionData,
  listActionDivisorData,
} from "@/api/baseConfig/actionDivisor";
import {
  saveDecisions,
  getDecisionsByGroup,
  downTemplate,
} from "@/api/ruleConfig/decision";
import addCondition from "./add-conditiontj";
import { changeClashInfo } from "@/api/task";
import addAction from "./add-action";
import editCondition from "./edit-condition";
import constant from "@/api/constant";
import axios from "axios";
import Vue from "vue";
import { listConditionDivisorData } from "@/api/baseConfig/conditionDivisor";
import cloneDeep from 'lodash/cloneDeep'

export default {
  data() {
    return {
      page: {
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
      },
      loading: false,
      divisormethodEnum: [],
      // isHeadtype0:false, //规则编码、规则名称表头不能编辑修改
      recodes: {
        isEntityEdit: false, //是否修改实体
        delHead: false, //是否删除列
        addHead: false, //是否新增列
        delRows: [], //是否删除行
        editRows: [], //是否修改行
        addRows: [], //是否新增行
      },
      conditionDivisorList: [],
      actionDivisorList: [],
      childList: {},
      enumList: {}, //条件枚举列表
      actionEnumList: {}, //动作枚举列表
      ruleList: [], //表头规则名称，编码
      tempHeaderList: [], //表头规则名称，编码
      isIndex: null,
      sysbols: constant.ruleConfig.sysbols,
      actionSysbols: constant.ruleConfig.actionSysbols,
      rightEntityItemInfos: [],
      excuteTypes: constant.ruleConfig.excuteTypes,
      adddataForm: [],
      addvisible: false,
      // addactionVisible: false,
      showDel: false,
      fileList: [],
      rowIndex: null, //行索引
      colIndex: null, //列索引
      condition: [], //当前表头信息
      delList: [], //当前表头信息
      delHeadList: [], //当前表头信息
      editConditionVisible: false,
      entityList: [],
      conditionList: [], //表头信息
      chooseIndex: 0,
      addConditionVisible: false,
      tableDatas: [], //决策表数据
      groupTypes: constant.ruleConfig.groupTypes,
      addOrUpdateVisible: false,
      // checkEntity: [],
      dataList: [],
      isDisabled: false,
      visible: false,
      entitysProperties: [],
      dataRule: {},
    };
  },
  created() {
    let id = this.$route.params.id;
    this.init(id);
  },
  watch: {
    adddataForm: {
      handler: function (newVal, oldVal) {
        this.adddataForm = newVal;
      },
      deep: true,
    },
  },
  props: {
    versionType: {
      type: String,
    },
    dataForm: {
      type: Object,
    },
    checkEntity: {
      type: Array,
    },
    isconflict: {
      type: Boolean,
    },
  },
  components: {
    addCondition,
    editCondition,
    addAction,
  },

  mounted() {
    //   // console.log(this.dataForm,'dataForm');
  },
  methods: {
    // 每页数
    sizeChangeHandle(val) {
      this.page.pageSize = val;
      this.page.pageIndex = 1;
    },
    // 当前页
    currentChangeHandle(val) {
      this.page.pageIndex = val;
    },
    //编辑表头
    ruleEdit(data,index) {
      // console.log(data);
      this.chooseIndex = index;

      let headData = this.conditionList[this.chooseIndex];
      if (headData.headType === "1") {
        this.addConditionVisible = true;
        this.$nextTick(() => {
          this.$refs.addCondition.init();
        });

      } else if (headData.headType === "2") {
        this.addactionVisible = true;
        this.$nextTick(() => {
          this.$refs.addaction.init();   
        });
      }
    },

    // 上传excel
    submitUpload(file) {
      // console.log("上传" + file.name);
      if (file.name == "") {
        this.$message.warning("请选择要上传的文件！");
        return false;
      }
      let taskInfo = this.$store.state.checktaskInfo;
      let fileFormData = new FormData();
      fileFormData.append("uploadFile", file, file.name);
      fileFormData.append("groupIdentify", this.dataForm.groupIdentify);
      fileFormData.append("taskNo", taskInfo.taskNo);
      fileFormData.append("conditionList", JSON.stringify(this.conditionList));
      fileFormData.append("tableDatas", JSON.stringify(this.tableDatas));
      const instance = axios.create({
        withCredentials: true, // 一定要加这个，不用设置什么请求头
        headers: {
          "Content-Type": "multipart/form-data",
          token: Vue.cookie.get("token"),
        },
      });
      this.$store.dispatch("loading/CHANGE_LOADING", true);
      instance
        .post(
          constant.DR + "/rule/ruleDecisionHeaderInfo/doImport",
          fileFormData
        )
        .then((res) => {
          // console.log(res);
          this.$store.dispatch("loading/CHANGE_LOADING", false);
          if (res.data && res.data.resultCode == constant.SUCCESS) {
            this.$message.success(res.data.resultMsg);

            res.data.data.forEach((item) => {
              // console.log(item.RCODE);
              let flag = false;
              let newData = [];
              this.tableDatas.forEach((t) => {
                if (item.RCODE.conditionDesc && item.RCODE.conditionDesc === t.RCODE.conditionDesc) {
                  this.conditionList.forEach((head) => {
                    item[head.decisionCode].id = t[head.decisionCode].id;
                  });
                  newData.push(item);
                  flag = true;
                } else {
                  newData.push(t);
                }
              });
              this.tableDatas = newData;
              if (!flag) {
                this.tableDatas.push(item);
              }
            });
            // console.log(this.tableDatas);
          } else {
            this.$message.error(res.data.resultMsg);
          }
        })
        .catch((err) => {
          this.$store.dispatch("loading/CHANGE_LOADING", false);
        });
    },
    beforeAvatarUpload(file) {
      if (this.conditionList.length <= 0) {
        this.$message.error("请添加表头信息");
        return false;
      }
      const isExcel =
        file.type ===
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
      const isLt2M = file.size / 1024 / 1024 < 5;

      if (!isExcel) {
        this.$message.error("上传文件只能是 xls或xlsx 格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传文件大小不能超过 5MB!");
        return false;
      }

      this.submitUpload(file);

      return true;
    },
    downExcel() {
      if (this.conditionList.length <= 0) {
        this.$message.error("请添加表头信息");
        return;
      }
      let taskInfo = this.$store.state.checktaskInfo;
      let params = {
        groupIdentify: this.dataForm.groupIdentify,
        taskNo: taskInfo.taskNo,
      };
      this.$store.dispatch("loading/CHANGE_LOADING", true);
      downTemplate(params)
        .then((res) => {
          // console.log(res,'res');
          this.$store.dispatch("loading/CHANGE_LOADING", false);
        })
        .catch((err) => {
          this.$store.dispatch("loading/CHANGE_LOADING", false);
        });
    },

    getItemValue(row, column) {
      if (
        row[column.property].isExcute != undefined &&
        row[column.property].isExcute != ""
      ) {
        if (row.isExcute === "Y") {
          return "已选择";
        } else if (row.isExcute === "N") {
          return "未选择";
        }
      }
      return row[column.property].conditionDesc;
    },
    labelHead: function (h, { column, $index }) {
      let l = column.label.length;
      let f = 16;
      column.minWidth = f * (l + 4); //加上4个文字长度
      let label = "";
      let label1 = this.conditionList[$index].headType;
      let isHeadtype0 = false;
      if (label1 === "0") {
        label = column.label;
        isHeadtype0 = false;
      } else if (label1 === "1") {
        label = `${column.label}(条件)`;
        isHeadtype0 = true;
      } else if (label1 === "2") {
        label = `${column.label}(动作)`;
        isHeadtype0 = true;
      }
      return h("div", [
        label,
        h("span", [
          h("i", {
            class: {
              "el-icon-circle-close rule-edit": this.showDel && isHeadtype0,
            },
            on: {
              click: (_) => {
                this.delcol(column);
              },
            },
          }),
        ]),
        h("span", [
          h("i", {
            class: {
              "el-icon-edit rule-edit": this.showDel && isHeadtype0,
            },
            on: {
              click: (_) => {
                this.ruleEdit(column,$index);
              },
            },
          }),
        ]),
      ]);
    },
    delDecision(data) {
      // console.log(data);
      this.$confirm(`确定进行[删除]操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.tableDatas.splice(data.$index, 1);
          let row = data.row;
          this.conditionList.forEach((item) => {
            if (row[item.decisionCode].id) {
              this.delList.push(row[item.decisionCode]);
            }
          });
          // console.log(this.delList);
        })
        .catch(() => { });
    },
    // 记录输入的值
    insertV(type, data, val) {
      // debugger
      //规则因子 输入值
      if (type === "41") {
        data.descData[0] = { k: data.rightValue, v: data.rightValue };
      }
      if (type === "45") {
        // 规则因子 输入值
        data.descData[0] = { k: val.name, v: val.name };
      }
      //枚举
      if (type === "42") {
        data.descData[0] = { k: data.enumValue, v: data.enumCode };
        // console.log(this.adddataForm);
      }
      //模型
      if (type === "43") {
        data.descData[0] = {
          k: val.entityName + " 的",
          v: "$" + val.entityIdentify + ".",
        };
        this.changeRightEntity(val);
      }
      //属性
      if (type === "44") {
        let s =
          val.itemIdentify.substring(0, 1).toLocaleUpperCase() +
          val.itemIdentify.substring(1, val.itemIdentify.length);
        let v = "get" + s + "()";
        data.descData[1] = { k: val.itemName, v: v };
      }
      // console.log(type, data, val);
    },
    //选择实体类
    changeRightEntity(item) {
      let params = {
        id: item.entityId + "",
      };
      let name = item.entityId + "list";
      this.childList[name] = [];
      entityItemList(params).then((res) => {
        if (res.data.data) {
          res.data.data.forEach((item) => {
            item["label"] = item.itemName + "--" + item.itemIdentify;
            this.childList[name].push(item);
          });
          // console.log(this.childList);
          this.$forceUpdate();
        }
      });
    },
    // 是否执行
    changeExeType(item, index) {
      if (item.isExcute === "N") {
        // this.$set(this.adddataForm[index], "showMthod", false);
        // this.$set(this.adddataForm[index], "showTxt", false);
        // this.$set(this.adddataForm[index], "showSysbol", false);
      } else {
        this.$set(this.adddataForm[index], "showMthod", true);
        this.$set(this.adddataForm[index], "showTxt", true);
        this.$set(this.adddataForm[index], "showSysbol", true);
      }
      this.$set(this.adddataForm[index], "isExcute", item.isExcute);
      // console.log(this.adddataForm);
    },

    //获取实体属性
    getItems(rightEntityId) {
      let params = {
        id: rightEntityId + "",
      };
      let name = rightEntityId + "list";
      let arr = [];
      entityItemList(params).then((res) => {
        if (res.data.data) {
          res.data.data.forEach((item) => {
            item["label"] = item.itemName + "--" + item.itemIdentify;
            // this.rightEntityItemInfos.push(item);
            arr.push(item);
          });
          this.childList[name] = arr;
          // console.log(this.childList);
        }
      });
    },
    initDivisor() {
      let params = {
        is_effect: "1",
      };
      listConditionDivisorData(params).then((res) => {
        this.conditionDivisorList = res.data.data;
      });
      listActionDivisorData(params).then((res) => {
        this.actionDivisorList = res.data.data;
      });
    },
    //初始化行数据 dataForm 数据 ，item 头部信息,headType条件、动作
    setInitData(dataForm, item, ele) {
      //如果是因子
      if (dataForm && dataForm.conditionType === "4") {
        let parms = { id: dataForm.divisorId };
        if (dataForm.headType && dataForm.headType === "1") {
          // console.log(this.conditionDivisorList);
          this.conditionDivisorList.forEach((item) => {
            // console.log(item.id,dataForm.divisorId);
            if (item.id === dataForm.divisorId) {
              dataForm.divisor = item;
              if (dataForm.divisor.methodParams) {
                // console.log(dataForm.divisor.methodParams,'222');
                // console.log(this.adddataForm);
                // dataForm.showMthod = true;
                if (dataForm.methodParams) {
                  // dataForm.divisorMethodParams = JSON.parse(
                  //   dataForm.methodParams
                  // );
                  dataForm.divisorMethodParams = [];
                  let m = JSON.parse(dataForm.methodParams);
                  let arr = JSON.parse(dataForm.divisor.methodParams);
                  for (var i = 0; i < m.length; i++) {
                    let mp = m[i];
                    mp["attri"] = arr[i].name;
                    dataForm.divisorMethodParams.push(mp);
                  }
                } else {
                  // dataForm.divisorMethodParams = JSON.parse(
                  //   dataForm.divisor.methodParams
                  // );
                  dataForm.divisorMethodParams = [];
                  let arr = JSON.parse(dataForm.divisor.methodParams);
                  arr.forEach((item) => {
                    item["attri"] = item.name;
                    item["name"] = "";
                    dataForm.divisorMethodParams.push(item);
                  });
                }
              } else {
                dataForm.divisorMethodParams = "";
              }
              if (dataForm.divisor.divisorType === "0") {
                // 输入值
                if (dataForm.divisor.valueType === "2") {
                  dataForm.showTxt = true;
                }
                //模型
                if (dataForm.divisor.itemValueType === "3") {
                  if (dataForm.rightEntityId) {
                    this.getItems(dataForm.rightEntityId);
                  }
                }
              }
            }
          });
          if (dataForm.divisor && dataForm.divisor.itemValueType === "2") {
            let name = dataForm.divisor.id + "list";
            let arr = [];
            getData(parms).then((res) => {
              res.data.data.enumList.forEach((item) => {
                item["label"] = item.enumCode + "--" + item.enumValue;
                arr.push(item);
              });
              this.enumList[name] = arr;
              // console.log(this.enumList);
              this.$forceUpdate();
            });
          }
        }
        if (dataForm.headType && dataForm.headType === "2") {
          this.actionDivisorList.forEach((item) => {
            if (item.id === dataForm.divisorId) {
              dataForm.divisor = item;
              if (dataForm.divisor && dataForm.divisor.methodParams) {
                if (dataForm.methodParams) {
                  // dataForm.divisorMethodParams = JSON.parse(
                  //   dataForm.methodParams
                  // );
                  dataForm.divisorMethodParams = [];
                  let m = JSON.parse(dataForm.methodParams);
                  let arr = JSON.parse(dataForm.divisor.methodParams);
                  for (var i = 0; i < m.length; i++) {
                    let mp = m[i];
                    mp["attri"] = arr[i].name;
                    dataForm.divisorMethodParams.push(mp);
                  }
                } else {
                  dataForm.divisorMethodParams = [];
                  let arr = JSON.parse(dataForm.divisor.methodParams);
                  arr.forEach((item) => {
                    item["attri"] = item.name;
                    item["name"] = "";
                    dataForm.divisorMethodParams.push(item);
                  });
                }
              }
              if (dataForm.divisor && dataForm.divisor.divisorType === "1") {
                dataForm.showMthod = true;
                // if (dataForm.conditionDesc) {
                //   let param = [];
                //   param = dataForm.conditionDesc.split(",");
                //   if (dataForm.divisor.methodParams) {
                //     dataForm.divisorMethodParams = JSON.parse(
                //       dataForm.divisor.methodParams
                //     );
                //     param.forEach((e, i) => {
                //       // debugger
                //       dataForm.divisorMethodParams[i]["attri"] =
                //         dataForm.divisorMethodParams[i].name;
                //       dataForm.divisorMethodParams[i].name = e;
                //     });
                //   }
                // }
              } else if (dataForm.divisor.divisorType === "0") {
                // 输入值
                if (dataForm.divisor.valueType === "2") {
                  // dataForm.showTxt = true;
                }
                //模型
                if (dataForm.divisor.itemValueType === "3") {
                  if (dataForm.rightEntityId) {
                    this.getItems(dataForm.rightEntityId);
                  }
                }
              }
            }
          });
          if (
            dataForm &&
            dataForm.divisor &&
            dataForm.divisor.itemValueType === "2"
          ) {
            let name = dataForm.divisor.id + "list";
            let arr = [];
            getActionData(parms).then((res) => {
              res.data.data.enumList.forEach((item) => {
                item["label"] = item.enumCode + "--" + item.enumValue;
                arr.push(item);
              });
              this.actionEnumList[name] = arr;
              // console.log(this.actionEnumList);
              this.$forceUpdate();
            });
          }
        }
        if ((dataForm.divisor.divisorType === "1" || dataForm.divisor.divisorType === "3") && dataForm.divisor.methodParams) {
          dataForm.showMthod = true;
          dataForm.divisormethodEnum = [];
          let divisormethodParams = JSON.parse(dataForm.divisor.methodParams);
          divisormethodParams.forEach((e, i) => {
            dataForm.divisormethodEnum[i] = [];
            if (e.valueType === "2") {
              // console.log(dataForm.divisor.methodParams);
              let parms = {
                divisor_identify:
                  dataForm.divisorIdentify || dataForm.divisor.divisorIdentify,
                param_name: divisormethodParams[i].name,
              };
              getEnum(parms).then(({ data }) => {
                // console.log(data);
                if (data.resultCode === 0) {
                  data.data.forEach((item) => {
                    item["label"] = item.enumCode + "--" + item.enumValue;
                    item["value"] = item.enumCode;
                    dataForm.divisormethodEnum[i].push(item);
                  });
                }
              });
              // console.log(dataForm, "222");
            }
            this.$forceUpdate();
          });
        }
      } else {
      }

      // if (dataForm.isExcute === "N") {
      //     dataForm.showTxt = false;
      //     dataForm.showSysbol = false;
      //     // dataForm.showMthod = false;
      // }

      return dataForm;
    },
    // 新增/修改行
    addRow(ele, index) {
      // console.log(ele, index,'ele, index');
      // console.log(this.conditionList,this.tableDatas);
      if (this.tempHeaderList.length <= 0) {
        this.$message.error("请添加表头信息");
        return;
      }
      if (index != undefined) {
        index = this.page.pageSize * (this.page.pageIndex - 1) + index;
      }
      this.isIndex = index;
      this.addvisible = true;
      this.adddataForm = [];

      if (this.isIndex != undefined && this.isIndex >= 0) {
        // console.log(this.tableDatas[this.isIndex], "22");
        let data = JSON.parse(JSON.stringify(this.tableDatas[this.isIndex]));
        this.conditionList.forEach((item) => {
          if (item) {
            if (data) {
              for (const key in data) {
                if (item.decisionCode == key) {
                  // console.log(data[key]);
                  data[key]["headType"] = item.headType;
                  data[key].divisorId = item.divisorId;
                  if (item.conditionType) {
                    data[key].conditionType = item.conditionType;
                  }
                }
              }
            }
            //   // console.log(item,data,'xzhsss');
            let dataForm = {};
            //    if (data[item.decisionCode] && data[item.decisionCode].conditionType) {
            // console.log(dataForm, "111");
            dataForm = this.setInitData(data[item.decisionCode], item);
            //    }
            if (dataForm && dataForm.remark) {
              dataForm["descData"] = new Array();
              dataForm["descData"] = JSON.parse(dataForm.remark);
            }
            if (dataForm && item && item.conditionDesc) {
              dataForm["conditionDesc1"] = item.conditionDesc;
            }
            this.adddataForm.push(dataForm);
          }
        });
      } else {
        let dataForm = {
          id: null,
          isExcute: "", //默认执行
          conditionType: "",
          divisorId: null,
          leftProperty: null,
          rightProperty: null,
          leftEntityId: null,
          rightEntityId: null,
          sysbol: "",
          rightValue: "",
          decisionExp: "",
          conditionExpression: "",
          conditionDesc: "",
          ["conditionDesc1"]: "",
          conditionMethodType: "",
          methodParams: "",
          isEffect: null,
          methodName: "",
          remark: "",
          descData: new Array(),
          showMthod: true,
          methodParas: [],
          showTxt: false,
          showSysbol: false,
          divisor: {
            valueType: "",
            rightEntityId: null,
            rightProperty: null,
            rightValue: "",
            configDate: null,
            configUser: null,
            creTime: null,
            creUserId: null,
            divisorIdentify: null,
            divisorMethod: null,
            divisorName: null,
            divisorType: null,
            entityId: null,
            id: null,
            isEffect: null,
            itemId: null,
            itemIdentify: null,
            itemTxtLength: null,
            itemTxtType: null,
            itemValueType: null,
            methodDesc: null,
            methodExpression: null,
            methodParams: null,
            methodType: null,
            remark: null,
            sysbol: null,
          },
        };

        this.conditionList.forEach((item) => {
          // console.log(item);
          dataForm = JSON.parse(JSON.stringify(item));
          dataForm.isExcute = ""; //设置默认执行
          dataForm["conditionDesc1"] = dataForm.conditionDesc;
          dataForm.methodParams = null
          dataForm = this.setInitData(dataForm, item);
          dataForm.descData = new Array();
          dataForm.id = null;
          if (dataForm.decisionCode === "RCODE") {
            dataForm.conditionDesc = "";
          }
          if (dataForm.decisionCode === "RNAME") {
            dataForm.conditionDesc = "";
          }

          this.adddataForm.push(dataForm);
        });
      }
      // console.log(this.adddataForm, "this.adddataForm.");

      this.isadddataForm();
    },
    getgetEnum() { },
    isadddataForm() {
      // 是否显示执行 固定值显示 方法没有参数显示
      this.adddataForm.forEach((e) => {
        if (e) {
          if (!e.divisor) {
            e.iszhixing = false;
          } else {
            // 非方法，固定值
            if (e.divisor && e.divisor.divisorType == "0") {
              if (!e.divisor.valueType || e.divisor.valueType == "1") {
                e.iszhixing = true;
              } else {
                e.iszhixing = false;
              }
            } else if (e.divisor && e.divisor.divisorType == "1") {
              // console.log(e, "1234");
              // 方法
              if (e.divisor.methodParams) {
                let param = JSON.parse(e.divisor.methodParams);
                if (param.length) {
                  e.iszhixing = false;
                } else {
                  e.iszhixing = true;
                }
              } else {
                e.iszhixing = true;
              }
            }
          }
        }
      });
      // console.log(this.adddataForm);
    },
    //0禁用、1启用
    editIsEffect(value, type) {
      // console.log(value);
      // console.log(this.conditionList);
      let msg = "";
      if (type === 0) {
        msg = "禁用";
      } else {
        msg = "启用";
      }
      this.$confirm("确定要" + msg + "此列吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.conditionList.forEach((ele) => {
            if (value.row[ele.decisionCode].isEffect == "1") {
              value.row[ele.decisionCode].isEffect = "0";

              if (ele.decisionCode === "RCODE") {
                value.row[ele.decisionCode].editType = constant.DEL; //删除
              }
            } else if (value.row[ele.decisionCode].isEffect == "0") {
              value.row[ele.decisionCode].isEffect = "1";

              if (ele.decisionCode === "RCODE") {
                value.row[ele.decisionCode].editType = constant.EDIT; //修改
              }
            }
          });
        })
        .catch(() => { });
    },
    //删除列
    delcol(col) {
      this.conditionList = this.conditionList;
      this.$confirm("确定要删除此列吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //记录删除列
          this.recodes.delHead = true;

          let newHead = [];
          //头部信息
          this.tempHeaderList.forEach((item) => {
            if (item.decisionCode === col.property) {
              if (item.id) {
                this.delHeadList.push(item);
              }
            } else {
              newHead.push(item);
            }
          });
          this.tempHeaderList = newHead;
          this.initHeader();

          //数据信息
          let newBody = [];
          this.tableDatas.forEach((item) => {
            if (item[col.property]) {
              if (item[col.property].id) {
                this.delList.push(item[col.property]);
              }
              item[col.property] = null;
            }
            newBody.push(item);
          });
          this.tableDatas = newBody;

          // this.tableDatas = this.tableDatas.filter(t=>t.decisionCode!=col.property)
          // this.conditionList = this.conditionList.filter(c=> c.decisionCode!=col.property)
          this.showDel = false;
          // console.log(this.tableDatas);
          // console.log(this.conditionList);
        })
        .catch(() => { });
    },

    //校验数据
    validForm() {
      for (let i = 0; i < this.adddataForm.length; i++) {
        let dataForm = this.adddataForm[i];
        // 过滤空数据
        if (!dataForm) {
          continue;
        }
        if (dataForm.isExcute === "Y" && dataForm.headType != "0") {
          if (dataForm.conditionType === "4") {
            if (
              dataForm.divisor.divisorType === "0" &&
              dataForm.divisor.valueType === "2"
            ) {
              if (
                dataForm.divisor.itemValueType != "3" &&
                !dataForm.rightValue
              ) {
                // this.$message.error("请将因子补充完整");
                // return false;
                dataForm.isExcute = "N";
              }
              if (dataForm.divisor.itemValueType === "3") {
                //模型属性
                if (!dataForm.rightEntityId || !dataForm.rightProperty) {
                  dataForm.isExcute = "N";
                  // this.$message.error("请将模型及属性补充完整");
                  // return false;
                }
              }
            } else {
              if (dataForm.divisorMethodParams && dataForm.divisorMethodParams.length > 0) {
                let num = 0;
                for (var j = 0; j < dataForm.divisorMethodParams.length; j++) {
                  let item = dataForm.divisorMethodParams[j];
                  let value = item.name;
                  if (!value) {
                    // this.$message.error("请输入" + item.desc);
                    // return false;
                    num++;
                  }
                  if (item.type === "int") {
                    const digit = /^[0-9]*$/;
                    if (!digit.test(value)) {
                      // this.$message.error(item.desc + "只能输入数字");
                      // return false;
                    }
                  }
                }
                //如果参数都没填 默认不执行
                if (num == dataForm.divisorMethodParams.length) {
                  dataForm.isExcute = "N";
                }
              }
            }
          }
        } else if (dataForm.isExcute != "Y" && dataForm.headType != "0") {
          //因子类型
          if (dataForm.conditionType === "4") {
            //0-非方法 2-输入值
            if (dataForm.divisor.divisorType === "0" && dataForm.divisor.valueType === "2") {
              //1-文本，2-枚举 3-模型
              if (dataForm.divisor.itemValueType != "3" && dataForm.rightValue) {
                dataForm.isExcute = "Y";
              }
              if (dataForm.divisor.itemValueType === "3") {
                //模型属性
                if (dataForm.rightEntityId && dataForm.rightProperty) {
                  dataForm.isExcute = "Y";
                }
              }
            } else {
              if (dataForm.divisorMethodParams && dataForm.divisorMethodParams.length > 0) {
                let num = 0;
                for (var j = 0; j < dataForm.divisorMethodParams.length; j++) {
                  let item = dataForm.divisorMethodParams[j];
                  let value = item.name;
                  if (value) {
                    num++;
                  }
                }
                //如果参数都填 默认执行
                if (num == dataForm.divisorMethodParams.length) {
                  dataForm.isExcute = "Y";
                }
              }
            }
          }
        }
      }
      return true;
    },
    //设置表格显示的数据
    showValue(dataForm) {
      // dataForm.conditionExpression = ''
      dataForm.conditionDesc = "";
      if (dataForm.descData) {
        let exp = dataForm.conditionExpression;
        dataForm.descData.forEach((item) => {
          if (item && item.v && item.k) {
            dataForm.conditionDesc = dataForm.conditionDesc + item.v + "";
            exp = exp + item.v;
          }
        });
        dataForm.decisionExp = exp;
      }
    },
    // 新增表单 记录新增还是修改
    adddataFormSubmit() {
      // console.log(this.adddataForm);
      if (this.tempHeaderList.length <= 0) {
        this.$message.error("请添加表头信息");
        return;
      }

      if (!this.validForm()) {
        return;
      }

      let params = {};
      this.conditionList.forEach((item) => {
        for (var i = 0; i < this.adddataForm.length; i++) {
          let dataFrom = this.adddataForm[i];
          // 过滤空数据
          if (!dataFrom) {
            continue;
          }
          if (item.decisionCode === dataFrom.decisionCode) {
            this.setValueData(dataFrom, item);

            //记录是修改还是新增
            if (this.isIndex != undefined && this.isIndex >= 0) {
              if (dataFrom.decisionCode === "RCODE") {
                dataFrom.editType = constant.EDIT; //修改
              }
            } else {
              if (dataFrom.decisionCode === "RCODE") {
                dataFrom.editType = constant.ADD; //新增
              }
            }

            params[dataFrom.decisionCode] = dataFrom;
            break;
          }
        }
      });

      if (this.isIndex != undefined && this.isIndex >= 0) {
        // this.tableDatas[this.isIndex]=params
        this.$set(this.tableDatas, this.isIndex, params);
      } else {
        this.tableDatas.push(params);
      }

      this.addvisible = false;
      // console.log(this.tableDatas);
      // console.log(this.conditionList);
    },

    // 最终赋值
    setValueData(dataFrom, item) {
      // console.log(dataFrom, item);
      dataFrom.remark = JSON.stringify(dataFrom.descData);
      if (dataFrom.conditionType === "4") {
        //因子
        if (dataFrom.isExcute === "Y") {
          //非方法
          if (dataFrom.divisor.divisorType === "0") {
            //因子类型为输入值
            if (dataFrom.divisor.valueType === "2") {
              if (dataFrom.divisor.itemValueType != "3") {
                //非模型
                dataFrom.conditionDesc = dataFrom.rightValue;
                dataFrom.decisionExp =
                  dataFrom.conditionExpression + dataFrom.rightValue;
              } else {
                this.showValue(dataFrom);
              }
            } else {
              //固定值
              dataFrom.conditionDesc = dataFrom.isExcute;
              dataFrom.decisionExp = dataFrom.conditionExpression;
            }
          } else {
            //方法参数处理
            if (dataFrom.divisorMethodParams) {
              let inputValue = "";
              let newValue = "";
              if (dataFrom.headType == "1") {
                newValue = "ClmUtil." + dataFrom.divisor.divisorMethod;
              } else {
                newValue = "ActionUtil." + dataFrom.divisor.divisorMethod;
              }

              for (var j = 0; j < dataFrom.divisorMethodParams.length; j++) {
                let value = dataFrom.divisorMethodParams[j].name;
                let params = dataFrom.divisorMethodParams[j].attri; //参数名称

                inputValue += value + ",";
                let p = "$" + params + "$";
                if (dataFrom.divisorMethodParams[j].type === "String") {
                  newValue = newValue.replace(p, '"' + value + '"');
                } else {
                  newValue = newValue.replace(p, value === "" ? "null" : value);
                }
              }
              inputValue = inputValue.substring(0, inputValue.length - 1);
              dataFrom.conditionDesc = inputValue;
              dataFrom.decisionExp = newValue;
              dataFrom.methodParams = JSON.stringify(
                dataFrom.divisorMethodParams
              );
              // console.log(dataFrom.methodParams);
            } else {
              dataFrom.conditionDesc = dataFrom.isExcute;
              dataFrom.decisionExp = dataFrom.conditionExpression;
            }
          }
        } else if (dataFrom.isExcute === "N") {
          dataFrom.conditionDesc = dataFrom.isExcute;
          //非方法
          if (dataFrom.divisor.divisorType === "0") {
            //因子类型为输入值
            if (dataFrom.divisor.valueType === "2") {
              if (dataFrom.divisor.itemValueType != "3") {
                //非模型
                dataFrom.conditionDesc = dataFrom.rightValue;
                dataFrom.decisionExp =
                  dataFrom.conditionExpression + dataFrom.rightValue;
              } else {
                this.showValue(dataFrom);
              }
            } else {
              //固定值
              dataFrom.conditionDesc = dataFrom.isExcute;
              dataFrom.decisionExp = dataFrom.conditionExpression;
            }
          } else {
            //方法参数处理
            if (dataFrom.divisorMethodParams) {
              let inputValue = "";
              let newValue = "";
              if (dataFrom.headType == "1") {
                newValue = "ClmUtil." + dataFrom.divisor.divisorMethod;
              } else {
                newValue = "ActionUtil." + dataFrom.divisor.divisorMethod;
              }
              // for (var j = 0; j < dataFrom.divisorMethodParams.length; j++) {
              //     let value = dataFrom.divisorMethodParams[j].name;
              //     let params = dataFrom.divisorMethodParams[j].attri;//参数名称
              //
              //     inputValue += value + ",";
              //     let p = "$" + params + "$";
              //     if(dataFrom.divisorMethodParams[j].type==="String"){
              //         newValue = newValue.replace(p, "\""+value+"\"");
              //     }else{
              //         newValue = newValue.replace(p, value);
              //     }
              // }
              // inputValue = inputValue.substring(0, inputValue.length - 1);
              dataFrom.conditionDesc = inputValue;
              dataFrom.decisionExp = newValue;
              dataFrom.methodParams = JSON.stringify(
                dataFrom.divisorMethodParams
              );
              // console.log(dataFrom.methodParams);
            } else {
              dataFrom.conditionDesc = dataFrom.isExcute;
              dataFrom.decisionExp = dataFrom.conditionExpression;
            }
          }
        } else {
          dataFrom.conditionDesc = dataFrom.isExcute;
        }
      }
    },

    //编辑表头
    editHeader() {
      this.showDel = true;
    },

    // 刷新表值
    getConditionData(data) {
      console.log(data);
      let newData = [];
      this.tableDatas.forEach((item, index) => {
        if (index == this.rowIndex) {
          item[data.decisionCode] = JSON.parse(JSON.stringify(data));
        }
        newData.push(item);
      });
      this.tableDatas = newData;
      // console.log(this.tableDatas);
    },

    //复制 新增一行决策表值
    addDecisionRow(ele, index) {
      index = this.page.pageSize * (this.page.pageIndex - 1) + index;
      this.editConditionVisible = true;
      if (this.tempHeaderList.length <= 0) {
        this.$message.error("请添加表头信息");
        return;
      }
      this.adddataForm = [];
      // let params = {};
      let data = JSON.parse(JSON.stringify(this.tableDatas[index]));
      this.conditionList.forEach((item) => {
        // console.log(data[item.decisionCode], "debugg");
        let dataForm = this.setInitData(data[item.decisionCode], item);
        dataForm.descData = new Array();
        dataForm.id = null;
        if (dataForm.decisionCode === "RCODE") {
          dataForm.conditionDesc = "";
          dataForm.decisionExp = "";
        }
        if (dataForm.remark != '') {
          dataForm.descData = JSON.parse(dataForm.remark);
        }
        dataForm["conditionDesc1"] = item.conditionDesc;
        // params[item.decisionCode] = dataForm
        this.adddataForm.push(dataForm);
      });
      this.addvisible = true;
      // console.log(this.adddataForm);
      this.isIndex = null;
      // console.log(this.tableDatas);
      // this.tableDatas.push(params);
      this.isadddataForm();
    },
    initHeader() {
      this.conditionList = [];
      // console.log(this.ruleList);
      this.ruleList.forEach((item) => {
        this.conditionList.push(item);
      });
      this.tempHeaderList.forEach((item) => {
        this.conditionList.push(item);
      });
    },
    // 关闭弹窗
    closeAddCondition() {
      this.addConditionVisible = false;
    },
    //刷新决策表头列表
    getConditionDataList(data) {
      console.log(data, this.conditionList);

      //记录新增头部
      this.recodes.addHead = true;
      if (this.chooseIndex != null) {//编辑表头
        // 获取该列在暂存的tempHeaderList位置
        let currentIndex = this.tempHeaderList.findIndex(item => {
          return item.conditionDesc === this.conditionList[this.chooseIndex].conditionDesc && item.conditionExpression === this.conditionList[this.chooseIndex].conditionExpression;
        })
        if(data && data.hasOwnProperty("seq") && (parseInt(data.seq) + 1) !== this.chooseIndex){
          // 判断当前的表头，并交换位置
          let changeContent = 0;
          let changeIndex = 0;
          if(parseInt(data.seq) > this.tempHeaderList.length) {
            changeContent = this.conditionList[this.conditionList.length - 1];
            changeIndex = this.tempHeaderList.findIndex(item => {
              return item.conditionDesc === changeContent.conditionDesc && item.conditionExpression === changeContent.conditionExpression;
            }) 
            this.$set(this.conditionList, this.chooseIndex, changeContent); 
            this.$set(this.conditionList, this.conditionList.length - 1, data);
          }else{
            changeContent = this.conditionList[parseInt(data.seq) + 1];
            changeIndex = this.tempHeaderList.findIndex(item => {
              return item.conditionDesc === changeContent.conditionDesc && item.conditionExpression === changeContent.conditionExpression;
            })  
            this.$set(this.conditionList, this.chooseIndex, changeContent); 
            this.$set(this.conditionList, parseInt(data.seq) + 1, data);
          }
          // 在tempHeaderList中也交换位置
          this.$set(this.tempHeaderList, currentIndex, changeContent);
          this.$set(this.tempHeaderList, changeIndex, data);
        }else{
          this.$set(this.conditionList, this.chooseIndex, data);
          this.$set(this.tempHeaderList, currentIndex, data);
        } 
      } else {
        // 新增
        if (this.tempHeaderList.length > 0) {
          let flag = false;
          this.tempHeaderList.forEach((item) => {
            if (
              item.conditionExpression === data.conditionExpression &&
              item.headType === data.headType
            ) {
              flag = true;
            }
          });
          if (flag) {
            this.$message.error("已存在相同表头信息，请重新添加");
            return;
          }
          let arr = [];
          this.tempHeaderList.forEach((e) => {
            arr.push(Number(e.decisionCode.replace("D000", "")));
          });
          // console.log(arr);
          let code = Math.max(...arr);
          data.decisionCode = "D000" + Number(code + 1);
        } else {
          data.decisionCode = "D000" + Number(this.tempHeaderList.length + 1);
        }

        if(data.hasOwnProperty("seq") && data.seq ) {
          // 在数组中新增
          if(parseInt(data.seq) >= this.tempHeaderList.length + 1){
            this.tempHeaderList.push(data);
          }else{
            this.tempHeaderList.splice(parseInt(data.seq) - 1,0,data);
          }
        }else{
          // 1为新增条件 另一个为新增动作
          data.headType === "1" ? this.tempHeaderList.unshift(data) : this.tempHeaderList.push(data);
        }

        // if (data.headType === "1") { //条件
        //   // this.conditionList.unshift(data);
        //   // 如果存在排序，则做多个判断来控制放入数组位置
          
        // } else { //动作
        //   if(data.hasOwnProperty("seq") && data.seq ) {
        //     if(parseInt(data.seq) >= this.tempHeaderList.length + 1){
        //       this.tempHeaderList.push(data);
        //     }else{
        //       this.tempHeaderList.splice(parseInt(data.seq) - 1,0,data);
        //     }
        //   }else{
        //     this.tempHeaderList.push(data);
        //   }
        //   // this.conditionList.push(data);

        // }

        this.initHeader();

        // console.log(this.tableDatas);
        // 已经新增的行 添加列
        if (this.tableDatas.length > 0) {
          this.tableDatas.forEach((item, index) => {
            item[data.decisionCode] = {
              id: null,
              isExcute: "Y", //默认不执行
              conditionType: "",
              divisorId: null,
              leftProperty: null,
              rightProperty: null,
              leftEntityId: null,
              rightEntityId: null,
              sysbol: "",
              rightValue: "",
              decisionExp: "",
              conditionExpression: "",
              conditionDesc: "",
              ["conditionDesc1"]: "",
              conditionMethodType: "",
              methodParams: "",
              isEffect: null,
              methodName: "",
              remark: "",
              descData: new Array(),
              showMthod: false,
              methodParas: [],
              showTxt: false,
              showSysbol: false,
              divisor: {
                configDate: null,
                configUser: null,
                creTime: null,
                creUserId: null,
                divisorIdentify: null,
                divisorMethod: null,
                divisorName: null,
                divisorType: null,
                entityId: null,
                id: null,
                isEffect: null,
                itemId: null,
                itemIdentify: null,
                itemTxtLength: null,
                itemTxtType: null,
                itemValueType: null,
                methodDesc: null,
                methodExpression: null,
                methodParams: null,
                methodType: null,
                remark: null,
                sysbol: null,
              },
            };
            item[data.decisionCode] = JSON.parse(JSON.stringify(data));
            item[data.decisionCode].conditionDesc = null;
            item[data.decisionCode].isExcute = "Y";
          });
        }
      }

      // console.log(this.tableDatas, this.conditionList);
    },

    //1-添加决策表条件列 2-添加决策表动作列
    addConditionCol(type) {
      // if (this.checkEntity.length <= 0) {
      //     this.$message.error("请关联实体");
      //     return;
      // }
      this.chooseIndex = null;
      if (type == "1") {
        this.addConditionVisible = true;
        // console.log(this.$refs.addCondition,'addCondition');
        this.$nextTick(()=> {
          this.$refs.addCondition.init();
        })
      } else if (type == "2") {
        this.addactionVisible = true;
        this.$nextTick(() => {  
          this.$refs.addaction.init();
        });
      }
    },

    toList() {
      constant.clearTag(this);
      this.$router.push({
        path: "/drools-ruleConfig/group/add-or-update/" + this.dataForm.id,
      });
    },

    //初始化规则组信息
    init(id) {
      this.visible = true;
      // 规则组冲突
      if (!this.isconflict) {
        this.initDecision();
      } else {
      }
      this.initDivisor();
      this.initRuleInfo();
      this.isDisabled = false;
      this.entitysProperties = [];
      // this.$nextTick(()=>{
      this.getEntityProperties();
      // })
      // this.checkEntity = this.dataForm.checkEntity;
    },

    //初始化表头规则名称规则编码
    initRuleInfo() {
      let ruleName = {
        decisionCode: "RNAME",
        conditionExpression: "规则名称",
        conditionDesc: "规则名称",
        headType: "0",
        groupIdentify: this.dataForm.groupIdentify,
      };
      let ruleCode = {
        decisionCode: "RCODE",
        conditionExpression: "规则编码",
        conditionDesc: "规则编码",
        headType: "0",
        groupIdentify: this.dataForm.groupIdentify,
      };
      this.ruleList.push(ruleCode);
      this.ruleList.push(ruleName);
    },
    // 获取编辑规则数据
    getChangeClashInfo(dataForm, decisionList) {
      let params = {
        groupIdentify: dataForm.groupIdentify,
        taskNo: dataForm.taskNo,
        decisionList: decisionList,
      };
      changeClashInfo(params).then((res) => {
        if (res.data.data) {
          this.tableDatas = res.data.data.body;
          // console.log(this.tableDatas, "eDatas");
          this.conditionList = res.data.data.head;

          //除去规则名称和编码的表头
          if (this.conditionList && this.conditionList.length > 0) {
            this.tempHeaderList = [];
            this.conditionList.forEach((item) => {
              if (
                item.decisionCode != "RNAME" &&
                item.decisionCode != "RCODE"
              ) {
                this.tempHeaderList.push(item);
              }
            });
          } else {
            this.ruleList.forEach((item) => {
              this.conditionList.push(item);
            });
          }
          // console.log("初始化头部信息:" + JSON.stringify(this.conditionList));
        }
      });
    },
    //初始化规则组下已有决策表信息
    initDecision() {
      let params = {
        groupIdentify: this.dataForm.groupIdentify,
        type: this.versionType,
        version: this.dataForm.groupVersion + "",
        taskNo: this.dataForm.taskNo,
      };
      //   if (localStorage.getItem("checktaskobj")) {
      //    let checktaskobj = JSON.parse(localStorage.getItem("checktaskobj"));
      //     params.taskNo = checktaskobj.taskNo;
      //   }
      // this.$store.dispatch("loading/CHANGE_LOADING", true);
      getDecisionsByGroup(params)
        .then((res) => {
          this.$store.dispatch("loading/CHANGE_LOADING", false);
          if (res.data.data) {
            this.tableDatas = res.data.data.body;
            this.tableDatas.forEach((e) => {
              if (e && e.RNAME && e.RNAME.conditionDesc == "") {
                e.RNAME.conditionDesc = e.RCODE.conditionDesc;
              }
            });
            // console.log(this.tableDatas, "eDatas");
            this.conditionList = res.data.data.head;

            //除去规则名称和编码的表头
            if (this.conditionList && this.conditionList.length > 0) {
              this.tempHeaderList = [];
              this.conditionList.forEach((item) => {
                if (
                  item.decisionCode != "RNAME" &&
                  item.decisionCode != "RCODE"
                ) {
                  this.tempHeaderList.push(item);
                }
              });
            } else {
              this.ruleList.forEach((item) => {
                this.conditionList.push(item);
              });
            }
            // console.log("初始化头部信息:" + JSON.stringify(this.conditionList));
          }
        })
        .catch((err) => {
          this.$store.dispatch("loading/CHANGE_LOADING", false);
        });
    },

    // 获取实体类的属性
    getEntityProperties() {
      entityList({}).then((res) => {
        if (res.data.data) {
          this.entitysProperties = [];
          res.data.data.forEach((item) => {
            item["label"] = item.entityIdentify + " -- " + item.entityName;
            this.entitysProperties.push(item);
          });

          if (this.isconflict) {
            this.entityList = [];
            this.entitysProperties.forEach((e) => {
              let entity = {
                entityName: e.entityName,
                entityIdentify: e.entityIdentify,
                entityId: e.entityId,
                pkgName: e.pkgName,
              };
              this.entityList.push(entity);
              // console.log(this.entityList,'entityList');
            });
          } else {
            this.entityList = [];
            this.checkEntity.forEach((item) => {
              this.entitysProperties.forEach((e) => {
                if (item.entityId === e.entityId) {
                  let entity = {
                    entityName: e.entityName,
                    entityIdentify: e.entityIdentify,
                    entityId: e.entityId,
                    pkgName: e.pkgName,
                  };
                  this.entityList.push(entity);
                  // console.log(this.entityList,'entityList');
                }
              });
            });
          }
        }
      });
    },

    // 表单提交
    dataFormSubmit() {
      // console.log(this.checkEntity);

      let values = [];
      if (this.tableDatas.length > 0) {
        for (var i = 0; i < this.tableDatas.length; i++) {
          let data = this.tableDatas[i];
          if (data) {
            this.conditionList.forEach((item) => {
              // console.log(data, this.conditionList);
              if (data[item.decisionCode]) {
                data[item.decisionCode]["rowIndex"] = i;
                values.push(data[item.decisionCode]);
              }
            });
          }
        }
      }
      // console.log(values);

      let params = {
        groupIdentify: this.dataForm.groupIdentify,
        heads: JSON.stringify(this.conditionList),
        values: JSON.stringify(values),
        delList: JSON.stringify(this.delList),
        delHeadList: JSON.stringify(this.delHeadList),
      };
      this.$store.dispatch("loading/CHANGE_LOADING", true);
      saveDecisions(params)
        .then((res) => {
          this.$store.dispatch("loading/CHANGE_LOADING", false);
          if (res.data && res.data.resultCode === 0) {
            this.$message({
              message: "操作成功",
              type: "success",
              duration: 1500,
              onClose: () => {
                this.visible = false;

                // this.$emit('refreshDataList')
                this.toList();
              },
            });
          } else {
            this.$message.error(res.data.resultMsg);
          }
        })
        .catch((err) => {
          this.$store.dispatch("loading/CHANGE_LOADING", false);
        });
    },
  },
  filters: {},
};
</script>

<style lang="scss">
/*设置表头样式*/
.contain .table-head {
  font-size: 14px !important;
}

.contain .el-table .cell,
.el-table th div {
  padding: 0 !important;
}
.contain .el-table .cell div {
  white-space: pre-line;
}

.el-table__row .el-form-item__content {
  margin-left: 0 !important;
}
#condition-dialog {
  .el-dialog__body {
    overflow: auto !important;
  }
}
.el-table__row .el-form-item {
  margin-bottom: 0 !important;
}

.yellow {
  background: yellow !important;
}

.red {
  background: red !important;
}
.rule-edit {
  margin-left: 5px;
}
.form-container {
  padding: 10px 15px;
}
.padding-button {
  padding: 10px 0;
}
.button-flex {
  display: flex;
}
</style>
